import React from 'react';
import {useSelector } from 'react-redux'


export default function ChatRoom(props) {
  
  let roomId = props.match.params.roomId

  let ownerUsername = window.localStorage.getItem('username')
  
  console.log('ownerUsername ' + ownerUsername);

  const chatItems = useSelector(state => state.chatData)
  
  function handleSend(event) {  

    let scrollContainer  = document.getElementById('ChatLine')
    let hScrollHeight = scrollContainer.scrollHeight
    scrollContainer.scrollTop = hScrollHeight

    let body = document.getElementById('sendBody').value

    let username = window.localStorage.getItem('username')

    let data = {
      roomId: roomId,
      from: username,
      to: 'world',
      payload: body
    }
    console.log("send data " + data);

    global.ws.send( JSON.stringify(data))

  }

  const ChatLine =  chatItems.map((chatItem) => {
      
    if (chatItem.from == ownerUsername) {
      return (
        <div className='flex flex-col justify-end items-end' key={chatItem.messageId}>
          <p className='text-sm mr-0'>send: {chatItem.from}</p>
          <p className='text-xl mr-0'>{chatItem.payload}</p>
        </div> 
      )
    } else {
      return (
        <div key={chatItem.messageId}>
          <p className='text-sm'>receiver: {chatItem.from}</p>
          <p className='text-xl'>{chatItem.payload}</p>
        </div> 
      )

    }

  })

  return (
    <div className="relative w-full h-full bg-white flex flex-col">

      <div>
        {props.children}
      </div>

      <div className="w-full h-16 flex items-center justify-between border-b-2 px-4 border-gray-200">
        <p className="block text-2xl">{roomId}</p>
        <div>
          tools
        </div>
      </div>


      <div id="ChatLine" className="h-full mb-24 overflow-y-scroll">
        {
          ChatLine
        }

      </div>
      
      
      <div className="w-full h-24">
        <textarea id="sendBody" className="block w-full text-md h-20 border-2 border-indigo-50 absolute bottom-16 right-0" cols="42" rows="2" />

        <button onClick={handleSend} className="block absolute w-36 h-12 border-2 border-indigo-100 rounded w-48 bottom-2 right-2" type="submit">发送</button>
      
      </div>
      
    </div>

  )
    
}
